import store from '@/store'

function checkAuthority(el, binding) {
  const { value } = binding
  const roles = store.getters && store.getters.roles

  if (value && value instanceof String) {
    const name = value.split('.') // 'contact.edit'
    const arr = roles[name[0]]
    const isAu = arr.findIndex((item) => {
      return item.value === name[1]
    })
    if (isAu === -1) {
      el.parentNode && el.parentNode.removeChild(el)
    }
  } else {
    throw new Error(`need roles! Like v-checkAuthority="contact.edit"`)
  }
}

export default {
  inserted(el, binding) {
    checkAuthority(el, binding)
  },
  update(el, binding) {
    checkAuthority(el, binding)
  }
}
